package router

import (
	"github.com/gin-gonic/gin"
	swaggerfiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go-malphite/app/api"
	"go-malphite/app/common/middleware"
	"go-malphite/docs"
)

func NewRouter() *gin.Engine {
	r := gin.Default()

	// 全局异常处理
	r.Use(middleware.Recover)

	// swagger
	docs.SwaggerInfo.BasePath = ""
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))

	return r
}

// SetupRouter 设置路由
func SetupRouter(r *gin.Engine) {
	group := r.Group("/api/v1")

	AddRouterByPing(r)
	AddRouterByAuth(group)
	AddRouterByUser(group)
	AddRouterByTodo(group)
}

// AddRouterByPing 添加ping路由
func AddRouterByPing(r *gin.Engine) {
	r.GET("/ping", api.GetPing)
}

// AddRouterByAuth 添加授权路由
func AddRouterByAuth(g *gin.RouterGroup) {
	r := g.Group("/captcha")

	r.GET("/login", api.GetCaptchaByLogin)
}

// AddRouterByUser 添加用户路由
func AddRouterByUser(g *gin.RouterGroup) {
	r := g.Group("/user")

	r.POST("/register", api.CreateUser)
	r.POST("/login", api.LoginUser)
	r.GET("/detail", middleware.AuthJWT(), api.GetDetailUser)
	r.POST("/update", middleware.AuthJWT(), api.UpdateUser)
	r.POST("/updateByName", middleware.AuthJWT(), api.UpdateUserByName)
	r.POST("/logout", middleware.AuthJWT(), api.LogoutUser)
	r.GET("/list", middleware.AuthJWT(), api.GetListUser)
	r.GET("/page", middleware.AuthJWT(), middleware.QueryPage(), api.GetPageUser)
	r.POST("/remove/:userId", middleware.AuthJWT(), api.RemoveUser)
}

// AddRouterByTodo 添加待办路由
func AddRouterByTodo(g *gin.RouterGroup) {
	r := g.Group("/todo")

	r.Use(middleware.AuthJWT())
	r.Use(middleware.IsExistsUser())

	r.POST("/", api.AddTodo)
	r.DELETE("/:id", api.RemoveTodo)
	r.PUT("/:id", api.UpdateTodo)
	r.GET("/:id", api.GetDetailTodo)
	r.GET("/list", middleware.IsAdminUser(), api.GetListTodo)
	r.GET("/page", middleware.QueryPage(), api.GetPageTodo)
}
